using System;
using System.Net;
using System.IO;
using System.Text;
using System.Diagnostics;

class DeepMixMoscowRadioDownloader
{
	static int currentFileSize = 0;
	static Stream responseStream = null;
	static byte[] inputBuffer = new byte[8192]; 
	static FileStream outputFileStream = null;
	static string sourceURL = null;
	static string destinationFolder = null;

	static int getRadioData()
	{
        if (null == responseStream)
        {
            try
            {
                WebResponse response = WebRequest.Create(sourceURL).GetResponse();
                if (null != response)
                {
                    responseStream = response.GetResponseStream();
                    if (null != responseStream)
                    {
                        responseStream.ReadTimeout = 5000;
                        return getRadioData();
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.Message);
            }
            return 0;
        }
        return responseStream.Read(inputBuffer, 0, inputBuffer.Length);
	}

	static bool saveReceivedBytes(int aSize)
	{
		if (aSize < 1)
		{
			return false;
		}

		if (null == outputFileStream)
		{
			string outputFileName = getNewFileName(destinationFolder);
			outputFileStream = new FileStream (outputFileName, FileMode.Create);
		}

		if (null != outputFileStream)
		{
			outputFileStream.Write(inputBuffer, 0, aSize);
			return true;
		}

		return false;
	}

    static void resetInputs()
    {
        responseStream.Close();
        outputFileStream.Dispose();
        outputFileStream = null;
        currentFileSize = 0;
    }

    static void resetOutputs()
	{
		outputFileStream.Close();
		outputFileStream.Dispose();
		outputFileStream = null;
		currentFileSize = 0;
	}

	static string getNewFileName(string aFolder)
	{
		return string.Format (@"{6}{0}{1}{2}_{3}{4}{5}.mp3", 
					DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
		    		DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second,
					aFolder);
	}

	static void Main(string[] args)
	{
        sourceURL = @"http://69.163.134.109:8128";
        destinationFolder = System.Reflection.Assembly.GetExecutingAssembly().Location;
        destinationFolder = System.IO.Path.GetDirectoryName(destinationFolder) + @"\";

		while (true)
		{
			int receivedBytes = getRadioData();

			if (0 < receivedBytes)
			{
				if (saveReceivedBytes(receivedBytes))
				{
					currentFileSize += receivedBytes;
					if (currentFileSize >= 13107200)
					{
						resetOutputs();
					}
				}
			}
		}
	}
}
